package regular;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class Ultility {

	public static GraphQuery getAutomaton(Path fileCacheQuery)
			throws IOException {

		FileReader fr = new FileReader(fileCacheQuery.toString());
		BufferedReader br = new BufferedReader(fr);
		String line = "";

		ArrayList<VertexQ> listV = new ArrayList<VertexQ>();

		VertexQ wildcard = null;
		while ((line = br.readLine()) != null) {
			String[] node = line.split("\t");
			VertexQ v = new VertexQ(node[0]);
			for (int i = 1; i < node.length; i++) {
				v.childrenState.add(new EdgeQ(node[i]));
			}

			if (!node[0].equals("_"))
				listV.add(v);
			else
				wildcard = v;
		}
		if (wildcard != null)
			listV.add(wildcard);

		br.close();

		if (listV.size() >= 2) {
			if (wildcard == null)
				return new GraphQuery(listV, listV.get(0), listV.get(listV
						.size() - 1));
			else
				return new GraphQuery(listV, listV.get(0), listV.get(listV
						.size() - 2));
		} else
			return null;

	}

	public static void cacheGraphQuery(Configuration conf) throws IOException {
		FileSystem fs = FileSystem.get(conf);
		Path hdfsPath = new Path(Initial.HDFS_GRAPH_QUERY);

		// upload the file to hdfs. Overwrite any existing copy.
		fs.copyFromLocalFile(false, true, new Path(Initial.LOCAL_GRAPH_QUERY), hdfsPath);

		DistributedCache.addCacheFile(hdfsPath.toUri(), conf);
	}

	public static ArrayList<Node> getListNode(String pathDir) throws IOException {
		FileSystem fs = FileSystem.get(Initial.CONF);
		Path hdfsPath = new Path(pathDir);
		FileStatus[] status = fs.listStatus(hdfsPath);	

		ArrayList<Node> listNode = new ArrayList<Node>();
		
		for (int i = 0; i < status.length; i++) {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					fs.open(status[i].getPath())));
			String line;			
			while ((line = br.readLine()) != null) {				
				listNode.add(new Node(Integer.parseInt(line)));
			}
			br.close();
		}
		
		return listNode;
	}
}
